import store from '@/store';
export function danWS(socketUrl){
    if (!socketUrl) return;
    this.socketUrl = socketUrl;//socket地址
	this.socketState = 0;//0未连接，1已连接，-1断开,-2连接不上
	this.msgQueue = [];//断开时，存储异步待发消息队列；
    this.socket = null;//socket资源
    this.reconnectT = null;//重连延迟器
    this.reconnectNum = 0;//重连次数
    this.reconnectNumLimit = 10;//最高重连次数
    this.heartTimeout = 60000;//心跳超时，超过这个时间无收到任何响应，则断开
    this.heartTimeoutT = null;//心跳检测延迟器
    this.serverTimeoutT = null;//超时延迟器
	this.connect();
}
//注册方法
Object.assign(danWS.prototype,{
	connect(){
        this.socket = new WebSocket(this.socketUrl);
        this.socket.onmessage = (msg) => { // 数据接收
            console.log(msg);
            this.heartCheck();
        }
        this.socket.onopen = (res)=>{ // 连接建立之后执行send方法发送数据
            this.reconnectNum = 0;
            this.heartCheck();
        }
        this.socket.onerror = (res)=>{ // 连接建立失败重连
            console.log('连接失败')
            this.reconnect();
        };
        this.socket.onclose = (e)=>{ // 关闭
            console.log('断开连接', e)
            this.reconnect();
        },
        store.dispatch('ws/initWS',this.socket);
	},
    send(data) { // 数据发送
        this.socket.send(JSON.stringify(data));
    },
    sendHeart(){
        this.send({type:'heart'});
    },
    reconnect(){
        if (this.reconnectNum > this.reconnectNumLimit) return;
        if (this.lockReconnect) return;
        this.reconnectNum++;
        this.lockReconnect = true;
        if (this.reconnectT) clearTimeout(this.reconnectT);
        this.reconnectT = setTimeout(()=>{
            this.connect();
            this.lockReconnect = false;
        },5000);
    },
    heartCheck(){
        this.heartTimeoutT && clearTimeout(this.heartTimeoutT);
        this.serverTimeoutT && clearTimeout(this.serverTimeoutT);
        this.heartTimeoutT = setTimeout(()=>{
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          //如果前端接收到消息，就会重置心跳，如果没收到，那么超时时间到后，就会自动断开
          //this.socket.send(JSON.stringify({type:'heart'}));
          this.sendHeart();
          this.serverTimeoutT = setTimeout(()=>{
            this.reconnect();
          }, this.heartTimeout);

        }, this.heartTimeout)
    }
})

